<?php
/**
 * @package LaravelBoot
 *
 * @internal
 *
 * @author mawenpei
 * @date 2019/3/18 14:53
 * @version
 */
namespace Modules\Service\Logic;

use App\Models\MobileRecharge;
use App\Models\MobileRechargeOrder;
use App\Models\Recharge;
use App\Models\RechargeOrder;
use App\Models\User;
use App\Models\UserCoupon;
use Carbon\Carbon;
use function foo\func;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class CouponLogic extends BaseLogic
{
    //查询可用优惠券
    public static function userCoupon($userId,$rechargeAmount,$rechargeId,$channel){
        try{

            if ($rechargeId) {
                if ($channel == "oil_recharge") {
                    //查询套餐
                    $rechargeData = Recharge::where("id", $rechargeId)->first();
                } elseif ($channel == 'mobile_recharge') {
                    //查询套餐
                    $rechargeData = MobileRecharge::where("id", $rechargeId)->first();
                } else {
                    return fail(1003, "参数值有误:channel");
                }
                //判断套餐是否为新人套餐
                if ($rechargeData->only_first == 1) {
                    if ($channel == 'oil_recharge') {
                        //查询充值记录
                        $rechargeOrderData = RechargeOrder::where("user_id", $userId)->first();
                    } elseif ($channel == 'mobile_recharge') {
                        $rechargeOrderData = MobileRechargeOrder::where("user_id", $userId)->first();
                    } else {
                        return fail(1003, '参数值有误:channel');
                    }
                    //判断是否是首次充值
                    if ($rechargeOrderData) {
                        return fail(1015, "该套餐为新人套餐,您已不是新用户,无法充值");
                    }
                }
                //计算套餐总价
                $amount = $rechargeData->months * $rechargeAmount;
                //可用优惠券
                $months = $rechargeData->months;
                $couponUsableData = UserCoupon::where(function ($query) use ($userId, $amount, $channel,$months) {
                    $query->where("user_id", $userId)->where('status',1)->where("channel", $channel)->where("months","<=",$months)->where("min_amount", "<=", $amount)->whereDate("finished_at", ">=", date('Y-m-d'));
                })
                    ->orderBy('amount', 'desc')
                    ->select("id", "title", "channel", "type", "amount", "finished_at", "started_at", "min_amount", "status")
                    ->get();
                $couponUsableArray = [];
                if ($couponUsableData->count() > 0) {
                    foreach ($couponUsableData as $item) {
                        if ($item['type'] == 1) {
                            $type = "代金券";
                        } else {
                            $type = "特权券";
                        }
                        $item['type'] = $type;
                        $item['use_text'] = "可用";
                        $item['area_text'] = "仅限套餐充值可用";
                        $item['use_status'] = 1;
                        $item['finished_text'] = date('Y-m-d', strtotime($item['finished_at'])) . '过期';
                        $couponUsableArray[] = $item;
                    }
                }
                //DB::connection()->enableQueryLog();//开启sql打印日志
                //不可用优惠券
                $couponDisabledData = UserCoupon::where("user_id", $userId)
                    ->where(function ($query) use ($userId, $amount, $channel) {
                        $query->where("channel", "!=", $channel)->whereDate("finished_at", ">=", date('Y-m-d'));
                    })
                    ->orWhere(function ($query) use($userId,$amount,$channel,$months){
                        $query->where("channel",$channel)->where("user_id", $userId)->where("months",">",$months)->whereDate("finished_at", ">=",date('Y-m-d'));
                    })
                    ->orWhere(function ($query) use($userId,$amount,$channel,$months){
                        $query->where("channel",$channel)->where("user_id", $userId)->where("months","<",$months)->where("min_amount",">",$amount)->whereDate("finished_at", ">=",date('Y-m-d'));
                    })
                    ->orderBy('amount', 'desc')
                    ->select("id", "title", "channel", "type", "months","amount", "finished_at", "started_at", "min_amount", "status")
                    ->get();
                //$logs = DB::getQueryLog();//打印sql
                $couponDisabledArray = [];
                if ($couponDisabledData->count() > 0) {
                    foreach ($couponDisabledData as $item) {
                        if ($item['type'] == 1) {
                            $type = "代金券";
                        } else {
                            $type = "特权券";
                        }
                        if ($channel!=$item['channel']){
                            $item['area_text'] = "油卡充值可用";
                        }elseif($item['months']>$months){
                            $item['area_text'] = $item['months']."个月及以上套餐可用";
                        }else{
                            $item['area_text'] = "满".$item['min_amount']."元可用";
                        }
                        $item['type'] = $type;
                        $item['use_text'] = "不可用";
                        $item['finished_text'] = '已失效';
                        $item['use_status'] = 0;
                        $couponDisabledArray[] = $item;
                    }
                }

                $couponArray = array_merge($couponUsableArray, $couponDisabledArray);
                $count = $couponUsableData->count();
            }else{
                $count = 0;
                $couponArray = [];
            }

            return success(["coupon_num"=>$count,"coupon_list"=>$couponArray]);
        }catch (\Exception $e){
            Log::error($e);
            return fail(500,"系统错误");
        }
    }

    //我的优惠券
    public static function userCouponAll($userId, $status,$page,$limit){
        try{
            //获取用户信息
            $userData = User::find($userId);
            if (!$userData)return fail(1014,"用户不存在");
            //用户全部优惠券
            if (empty($status)) {
                //用户全部优惠券
                $couponAllData = UserCoupon::where("user_id",$userId)
                    ->forPage($page,$limit)
                    ->orderBy('finished_at','desc')
                    ->select("id","title","channel","months","type","amount","finished_at","started_at","min_amount","status")
                    ->get();
                $couponCount = UserCoupon::where("user_id",$userId)->count();
            } else {
                //用户全部优惠券
                $couponAllDataModel = UserCoupon::where("user_id",$userId);
                $couponCountModel = UserCoupon::where("user_id",$userId);
                if (3 == $status) {
                    $couponAllDataModel->where('finished_at', '<', date('Y-m-d H:i:s'));
                    $couponCountModel->where('finished_at', '<', date('Y-m-d H:i:s'));
                } elseif(2 == $status) {
                    $couponAllDataModel->whereIn('status', [2, 4]);
                    $couponCountModel->whereIn('status', [2, 4]);
                } elseif(1 == $status) {
                    $couponAllDataModel->where('status', 1)->where('finished_at', '>', date('Y-m-d H:i:s'));
                    $couponCountModel->where('status', 1)->where('finished_at', '>', date('Y-m-d H:i:s'));
                } else {
                    $couponAllDataModel->where('status', $status);
                    $couponCountModel->where('status', $status);
                }
                $couponAllData = $couponAllDataModel
                    ->forPage($page,$limit)
                    ->orderBy('finished_at','desc')
                    ->select("id","title","channel","months","type","amount","finished_at","started_at","min_amount","status")
                    ->get();
                $couponCount = $couponCountModel->count();
            }
            //定义数组
            $couponArray = [];
            if ($couponAllData->count()>0) {
                foreach ($couponAllData as $item) {
                    if ($item['channel']=='' || $item['channel']=='all'){
                        $area_text = "全场通用";
                    }elseif($item['channel']=='oil_recharge'){
                        $area_text = $item['months']."个月油卡套餐可用";
                    }elseif($item['channel']=='mobile_recharge'){
                        $area_text = $item["months"]."个月话费套餐可用";
                    }else{
                        $area_text = "仅限商城可用";
                    }
                    if ($item['type'] == 1) {
                        $type = "代金券";
                    } else {
                        $type = "特权券";
                    }
                    if ($item['status'] == 1 && strtotime($item['finished_at']) >= time()) {
                        $finished_text = "未过期";
                        $status = "可用";
                        $use_status = 1;
                    } elseif (strtotime($item['finished_at']) < time()) {
                        $status = "不可用";
                        $finished_text = "已过期";
                        $use_status = 3;
                    } else {
                        $status = "不可用";
                        $finished_text = "已使用";
                        $use_status = 2;
                    }
                    if ($item['min_amount']==0){
                        $minTxt = "全场通用";
                    }else{
                        $minTxt = "满".$item['min_amount'].'可用';
                    }
                    $couponArray[] = [
                        "id" => $item['id'],
                        "title" => $item["title"],
                        "type" => $type,
                        "amount" => $item['amount'],
                        "finished_at" => date('Y-m-d', strtotime($item['finished_at'])),
                        "use_text" => $status,
                        "finished_text" => $finished_text,
                        "channel" => $item['channel'],
                        "area_text" => $area_text,
                        "use_status" => $use_status,
                        "min_amount" => $item['min_amount'],
                        "min_text" => $minTxt
                    ];
                }
            }
            return success(["count"=>$couponCount,"data"=>$couponArray]);
        }catch (\Exception $e){
            Log::error($e);
            return fail(500,"系统错误");
        }
    }
}